package com.monkey.demolist.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kyleduo.switchbutton.SwitchButton;
import com.monkey.demolist.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Description: 本地蓝牙适配器BluetoothAdapter
 * Author: Arthor
 * Date: 2017/10/21
 * Time: 11:42
 */

public class BlueToothActivity extends AppCompatActivity {

    private static final String TAG = "BlueToothActivity";

    /**
     * UI
     */
    private TextView bluetoothState;
    private SwitchButton switchButton;
    private SwitchButton discover;
    //已配对的蓝牙设备列表
    private ListView listView;

    /**
     * BlueTooth
     */
    private BluetoothAdapter bluetoothAdapter;
    private static final int REQUST_CODE = 0x01;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_tooth);

        initView();

        initBluetooth();

        getBluetoothState();

        openOrClose();

        setDiscover();


    }

    /**
     * 1 获取本地蓝牙的适配器
     */
    private void initBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    /**
     * 2 获取本地蓝牙的状态
     */
    private void getBluetoothState() {
        if (bluetoothAdapter == null) {
            Toast.makeText(BlueToothActivity.this, "本设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }

        //获取蓝牙名称
        String name = bluetoothAdapter.getName();
        //获取蓝牙MAC地址
        String address = bluetoothAdapter.getAddress();
        //获取当前蓝牙的状态
        int state = bluetoothAdapter.getState();
        String stateStr = "";
        switch (state) {
            case BluetoothAdapter.STATE_ON://打开状态12
                stateStr = "打开状态12";
                switchButton.setChecked(true);
                break;
            case BluetoothAdapter.STATE_TURNING_ON://正在打开11
                stateStr = "正在打开11";
                switchButton.setChecked(false);
                break;
            case BluetoothAdapter.STATE_TURNING_OFF://正在关闭13
                stateStr = "正在关闭13";
                switchButton.setChecked(false);
                break;
            case BluetoothAdapter.STATE_OFF://关闭状态10
                stateStr = "关闭状态10";
                switchButton.setChecked(false);
                break;
        }
        bluetoothState.setText("本地蓝牙名称:" + name + "\n"
                + "本地蓝牙MAC地址:" + address + "\n"
                + "本地蓝牙当前状态:" + stateStr);
    }

    /**
     * 3 打开/关闭蓝牙
     */
    private void openOrClose() {

        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 判断蓝牙是否已经打开
                    if (!bluetoothAdapter.isEnabled()) {
                        // 打开本地蓝牙设备
                        boolean openSuccess = bluetoothAdapter.enable();
                        if (openSuccess) {
                            Toast.makeText(BlueToothActivity.this, "蓝牙打开成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(BlueToothActivity.this, "蓝牙打开失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    // 判断蓝牙是否已经打开
                    if (bluetoothAdapter.isEnabled()) {
                        // 关闭本地蓝牙设备
                        boolean isClosed = bluetoothAdapter.disable();
                        if (isClosed) {
                            Toast.makeText(BlueToothActivity.this, "蓝牙关闭成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(BlueToothActivity.this, "蓝牙关闭失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });
    }

    /**
     * 3-2-1 打开蓝牙方式2
     */
    private void openBluetooth() {

        // 判断设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            Toast.makeText(BlueToothActivity.this, "本设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }

        // 判断蓝牙是否已经打开
        if (bluetoothAdapter.isEnabled()) {
            Toast.makeText(BlueToothActivity.this, "蓝牙已经打开", Toast.LENGTH_SHORT).show();
        } else {
            // 打开本地蓝牙设备
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUST_CODE);
        }
    }

    /**
     * 3-2-2 打开蓝牙方式2回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUST_CODE) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(BlueToothActivity.this, "蓝牙打开成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(BlueToothActivity.this, "蓝牙打开失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initView() {
        bluetoothState = ((TextView) findViewById(R.id.state));
        switchButton = ((SwitchButton) findViewById(R.id.switchBtn));
        discover = ((SwitchButton) findViewById(R.id.discover));
        listView = ((ListView) findViewById(R.id.listview));
    }

    /**
     * 4 是否允许被周围设备检测到
     *      有时候扫描不到某设备，这是因为该设备对外不可见或者距离远，需要设备该蓝牙可见，这样该才能被搜索到。可见时间默认值为120s，最多可设置300。
     */
    private void setDiscover() {

        discover.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    if (bluetoothAdapter.isEnabled()) {//确保蓝牙处于打开状态
                        if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
                            startActivity(discoverableIntent);
                        }
                    }
                }
            }
        });

    }

    /**
     * 5 获取已配对蓝牙设备
     */
    public void getBindDevice(View view) {

        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();

        List<String> data = new ArrayList<>();
        for (final BluetoothDevice device : bondedDevices) {
            data.add("name=" + device.getName() + "\n"
                    + "address=" + device.getAddress() + "\n"
                    + "type=" + device.getType() + "\n" +
                    "bluetoothClass=" + device.getBluetoothClass() + "\n"+
                    "Uuids=" + device.getUuids().toString() + "\n");

            new Thread(new Runnable() {
                @Override
                public void run() {
                    connect(device,null);
                }
            }).start();

        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
        listView.setAdapter(adapter);

    }

    /**
     * 6 扫描周边设备
     * @param view
     */
    public void scanDevice(View view) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//搜索发现设备
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化
        filter.setPriority(Integer.MAX_VALUE);//设置优先级
        this.registerReceiver(mBluetoothReceiver,filter);

        bluetoothAdapter.startDiscovery();
        Log.e(TAG, "scanDevice:" + "111111111");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothReceiver);
        if (bluetoothAdapter != null) bluetoothAdapter.cancelDiscovery();
    }

    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "onReceive:" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)){//每扫描到一个设备，系统都会发送此广播


            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                Log.e(TAG, "onReceive:" + "扫描完毕");
            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                Log.e(TAG, "onReceive:" + "扫描开始");
            }

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(scanDevice == null || scanDevice.getName() == null) return;
                Log.e(TAG, "name="+scanDevice.getName()+"address="+scanDevice.getAddress());
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { //状态改变时
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING://正在配对
                        Log.d("BlueToothTestActivity", "正在配对......");
                        break;
                    case BluetoothDevice.BOND_BONDED://配对结束
                        Log.d("BlueToothTestActivity", "完成配对");
                        break;
                    case BluetoothDevice.BOND_NONE://取消配对/未配对
                        Log.d("BlueToothTestActivity", "取消配对");
                    default:
                        break;
                }
            }
        }
    };

    private void connect(BluetoothDevice device, Handler handler){

        Log.e(TAG, "connect:" + "1111");
        if (device.getBondState() == BluetoothDevice.BOND_BONDED){//此设备已配对完成

            Log.e(TAG, "connect:" + "2222");
            try {
                BluetoothSocket bluetoothSocket = device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
                bluetoothSocket.connect();
                Log.e(TAG, "connect:" + "333");

            } catch (IOException e) {
                Log.e(TAG, "connect:" + "4444");
                e.printStackTrace();
            }

        }
    }



}


